import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/widget/common_widget.dart';
import 'package:sptapp/widget/custom_time_picker.dart';

class MonitorStaticChooseDateDialog extends StatefulWidget {
  final int selIndex;
  final Function onDateChange;
  final int selType;
  final List<DateTime>? times;
  const MonitorStaticChooseDateDialog({super.key, required this.selIndex, required this.onDateChange, required this.selType, this.times,});

  @override
  State<MonitorStaticChooseDateDialog> createState() => _MonitorStaticChooseDateDialogState();
}

class _MonitorStaticChooseDateDialogState extends State<MonitorStaticChooseDateDialog> {

   late int selIndex;
   late int selType;
   List<DateTime> dayTimes = [];
   List<DateTime> monthTimes = [];
   List<DateTime> customTimes = [];
   List<DateTime> yearTimes = [];
   DateTime cusTime = DateTime.now();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    selType = widget.selType;
    selIndex = widget.selIndex;

    DateTime now = DateTime.now();
    dayTimes = [DateTime.now()];

    DateTime start = DateTime(now.year, now.month, 1);
    DateTime end = DateTime(now.year, now.month+1, 0);
    monthTimes = [start,end];

    yearTimes = [DateTime(now.year, 1, 1),DateTime(now.year, 12, 31)];
    customTimes = [DateTime.now(),DateTime.now()];

    print('seltype=====${selIndex} ${widget.times}');
    if(widget.times != null && widget.times!.isNotEmpty){
      if(selIndex == 0){
        dayTimes = widget.times!;
      }else if(selIndex == 2){
        monthTimes = widget.times!;
      }else if(selIndex == 3){
        yearTimes = widget.times!;
      }else if(selIndex == 4 && widget.times!.length >1){
        startCustomIndex = 2;
        endCustomIndex = 2;
        selCustomIndex = 0;
        customTimes = widget.times!;
        cusTime = widget.times![0];
      }
    }

    _getYears();
    _getDays();
    _getMonths();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: selIndex ==4? 1080.w : 960.w,
      width: 1.sw,
      padding: EdgeInsets.symmetric(horizontal: 40.w),
      decoration: BoxDecoration(
          color: Color(0xff1e1d20),
          borderRadius: BorderRadius.only(topRight: Radius.circular(24.w),topLeft: Radius.circular(24.w))
      ),
      child: Column(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            child: Column(
              children: [
                Container(
                  height: 112.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text('Choose Date',style: TextStyle(
                          color: Colors.white,
                          fontSize: 32.sp,
                          fontWeight: FontWeight.w400
                      ),),
                      GestureDetector(
                        onTap: (){
                          SmartDialog.dismiss();
                        },
                        child: Image.asset('assets/common/common_close_w.png',width: 48.w,),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 1.w,
                  color: Color.fromRGBO(255, 255, 255, 0.1),
                )
              ],
            ),
          ),
          SizedBox(height: 32.w,),
          Container(
            height: 88.w,
            padding: EdgeInsets.symmetric(horizontal: 16.w,vertical: 12.w),
            decoration: BoxDecoration(
                color: Color.fromRGBO(255, 255, 255, 0.05),
                borderRadius: BorderRadius.circular(88.w)
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  onTap: (){
                    setState(() {
                      selIndex = 0;
                    });
                  },
                  child: Container(
                    width: 150.w,
                    height: 58.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: selIndex == 0? themeColor:Colors.transparent,
                        borderRadius: BorderRadius.circular(58.w)
                    ),
                    child: Text('Day'.tr,style: TextStyle(
                        color: selIndex == 0? Colors.white:Color.fromRGBO(255, 255, 255, 0.6),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                ),
                // GestureDetector(
                //   onTap: (){
                //     setState(() {
                //       selIndex = 1;
                //     });
                //     _getDatas();
                //   },
                //   child: Container(
                //     width: 150.w,
                //     height: 58.w,
                //     alignment: Alignment.center,
                //     decoration: BoxDecoration(
                //         color: selIndex == 1? Color.fromRGBO(255, 255, 255, 0.1):Colors.transparent,
                //         borderRadius: BorderRadius.circular(58.w)
                //     ),
                //     child: Text('Week',style: TextStyle(
                //         color: selIndex == 1? Colors.white:Color.fromRGBO(255, 255, 255, 0.6),
                //         fontSize: 24.sp,
                //         fontWeight: FontWeight.w600
                //     ),),
                //   ),
                // ),
                GestureDetector(
                  onTap: (){
                    setState(() {
                      selIndex = 2;
                    });
                  },
                  child: Container(
                    width: 150.w,
                    height: 58.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: selIndex == 2?themeColor:Colors.transparent,
                        borderRadius: BorderRadius.circular(58.w)
                    ),
                    child: Text('Month'.tr,style: TextStyle(
                        color: selIndex == 2? Colors.white:Color.fromRGBO(255, 255, 255, 0.6),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                ),
                GestureDetector(
                  onTap: (){
                    setState(() {
                      selIndex = 3;
                    });

                  },
                  child: Container(
                    width: 150.w,
                    height: 58.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: selIndex == 3? themeColor:Colors.transparent,
                        borderRadius: BorderRadius.circular(58.w)
                    ),
                    child: Text('Year'.tr,style: TextStyle(
                        color: selIndex == 3? Colors.white:Color.fromRGBO(255, 255, 255, 0.6),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                ),
                GestureDetector(
                  onTap: (){
                    setState(() {
                      selIndex = 4;
                    });

                  },
                  child: Container(
                    width: 150.w,
                    height: 58.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: selIndex == 4? themeColor:Colors.transparent,
                        borderRadius: BorderRadius.circular(58.w)
                    ),
                    child: Text('Custom'.tr,style: TextStyle(
                        color: selIndex == 4? Colors.white:Color.fromRGBO(255, 255, 255, 0.6),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                )
              ],
            ),
          ),
          Expanded(child: Container(
            // color: Colors.red,
            alignment: Alignment.center,
            child: _buildContent(),
          )),
          GestureDetector(
            onTap: (){

              if(widget.onDateChange!=null){
                if(selIndex == 0){
                  SmartDialog.dismiss();
                  widget.onDateChange(selIndex,selType,dayTimes);
                }else if(selIndex == 2){
                  SmartDialog.dismiss();
                  widget.onDateChange(selIndex,selType,monthTimes);
                }else if(selIndex == 3){
                  SmartDialog.dismiss();
                  widget.onDateChange(selIndex,selType,yearTimes);
                }else if(selIndex == 4){
                  if(selCustomIndex == 0){
                    startCustomIndex = 1;
                    if(endCustomIndex == 1){
                      if(customTimes[1].isBefore(customTimes[0])){
                        showToast('End Date must be greater than Start Date'.tr);
                        return;
                      }
                      SmartDialog.dismiss();
                      widget.onDateChange(selIndex,selType,customTimes);
                    }else{
                      selCustomIndex = 1;
                      _getMonths();
                      _getYears();
                      _getDays();
                    }
                  }else if(selCustomIndex == 1){
                    endCustomIndex = 1;
                    if(startCustomIndex == 1){
                      if(customTimes[1].isBefore(customTimes[0])){
                        showToast('End Date must be greater than Start Date'.tr);
                        return;
                      }
                      SmartDialog.dismiss();
                      widget.onDateChange(selIndex,selType,customTimes);
                    }else{
                      selCustomIndex = 0;
                      _getMonths();
                      _getYears();
                      _getDays();
                    }
                  }
                }
              }
            },
            child: Container(
              alignment: Alignment.center,
              height: 108.w,
              decoration: BoxDecoration(
                color: themeColor,
                borderRadius: BorderRadius.circular(8.w)
              ),
              child: Text('Continue'.tr,style: TextStyle(
                color: Colors.white,
                fontSize: 32.sp,
                fontWeight: FontWeight.w600
              ),),
            ),
          ),
          SizedBox(height: ScreenUtil().bottomBarHeight+16.w,)
        ],
      ),
    );
  }

  Widget _buildContent(){
    if(selIndex == 0 ){
      return CalendarDatePicker2(
        config: CalendarDatePicker2Config(
          calendarType: selIndex == 4? CalendarDatePicker2Type.range : CalendarDatePicker2Type.single,
          calendarViewMode: CalendarDatePicker2Mode.day,
          dayTextStyle: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w400,
            fontSize: 28.sp
          ),
          weekdayLabelTextStyle: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w400,
              fontSize: 28.sp
          ),
          controlsTextStyle: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w400,
              fontSize: 28.sp
          ),
          selectedDayHighlightColor: themeColor,
          todayTextStyle: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w400,
              fontSize: 28.sp
          ),
          disableModePicker: true,
          weekdayLabels: [
            'Su'.tr,
            'Mo'.tr,
            'Tu'.tr,
            'We'.tr,
            'Th'.tr,
            'Fr'.tr,
            'Sa'.tr
          ],
          nextMonthIcon: Container(),
          lastMonthIcon: Container(),
          // controlsHeight: 25
        ),
        value: dayTimes,
        onValueChanged: (dates){
          setState(() {
            dayTimes = dates;
          });
          print('选中的日期====$dayTimes');
        },
      );
    }
    if(selIndex == 2){
      return CustomTimePickerM(timeType: 1,onTimeSelected: (index,value){
        setState(() {
          selMonthSingle = index;
        });
        print('选择单独月份===  $selMonthSingle');
        DateTime now = DateTime(monthTimes[0].year, selMonthSingle + 1, monthTimes[0].day);
        DateTime start = DateTime(monthTimes[0].year, now.month, 1);
        DateTime end = DateTime(now.year, now.month+1, 0);
        monthTimes = [start,end];
      },values: months,selIndex: selMonthSingle,);
    }else if(selIndex == 3){
      return CustomTimePickerY(timeType: 1,onTimeSelected: (index,value){
        setState(() {
          selYearSingle = index;
        });
        DateTime start = DateTime(int.parse(years[selYearSingle]), 1, 1);
        DateTime end = DateTime(int.parse(years[selYearSingle]), 12, 31);
        yearTimes = [start,end];
        print('选择单独年份===  $selYearSingle');
      },values: years,selIndex: selYearSingle,);
    }
    return Container(
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.symmetric(vertical: 32.w),
            height: 80.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  onTap: (){
                    setState(() {
                      selCustomIndex = 0;
                    });
                    _getMonths();
                    _getDays();
                    _getYears();
                  },
                  child: Container(
                    width: 260.w,
                    height: 80.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(255, 255, 255, 0.1),
                        border: Border.all(color: Color.fromRGBO(255, 255, 255, 1),width: 1.w),
                        borderRadius: BorderRadius.circular(16.w)
                    ),
                    child: Text(selCustomIndex == 0|| startCustomIndex == 1 || startCustomIndex == 2? _getYMRStr(customTimes[0]):'Start Date'.tr,style: TextStyle(
                      color: selCustomIndex ==0 || startCustomIndex == 1?Colors.white: Color.fromRGBO(255, 255, 255, 0.5),
                      fontSize: 24.sp,
                      fontWeight: FontWeight.w400
                    ),),
                  ),
                ),
                Container(
                  height: 4.w,
                  width: 28.w,
                  color: Color.fromRGBO(255, 255, 255, 1),
                ),
                GestureDetector(
                  onTap: (){
                    setState(() {
                      selCustomIndex = 1;
                    });
                    _getMonths();
                    _getDays();
                    _getYears();
                  },
                  child: Container(
                    width: 260.w,
                    height: 80.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Color.fromRGBO(255, 255, 255, 0.1),
                      border: Border.all(color: Color.fromRGBO(255, 255, 255, 1),width: 1.w),
                      borderRadius: BorderRadius.circular(16.w)
                    ),
                    child: Text(selCustomIndex == 1|| endCustomIndex == 1 || endCustomIndex == 2? _getYMRStr(customTimes[1]): 'End Date'.tr,style: TextStyle(
                        color: selCustomIndex ==1 || endCustomIndex == 1?Colors.white:Color.fromRGBO(255, 255, 255, 0.5),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w400
                    ),),
                  ),
                )
              ],
            ),
          ),
          Expanded(child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(child: CustomTimePickerYMDM(timeType: 1,onTimeSelected: (index,value){
                setState(() {
                  monthSelindex = index;
                });
                if(selCustomIndex == 0){
                  customTimes[0] = DateTime(customTimes[0].year, index+1, customTimes[0].day);
                }else if(selCustomIndex == 1){
                  customTimes[1] = DateTime(customTimes[1].year, index+1, customTimes[1].day);
                }
                _getYears();
                _getMonths();
                _getDays();
              },values: months,selIndex: monthSelindex,)),
              Expanded(child: CustomTimePickerYMDD(timeType: 1,onTimeSelected: (index,value){
                setState(() {
                  daySelindex = index;
                  if(selCustomIndex == 0){
                    customTimes[0] = DateTime(customTimes[0].year, customTimes[0].month, int.parse(days[daySelindex]));
                  }else if(selCustomIndex == 1){
                    customTimes[1] = DateTime(customTimes[1].year, customTimes[1].month, int.parse(days[daySelindex]));
                  }
                });
                _getYears();
                _getMonths();
                _getDays();
              },values: days,selIndex: daySelindex,)),
              Expanded(child: CustomTimePickerYMDY(timeType: 1,onTimeSelected: (index,value){
                setState(() {
                  yearSelindex = index;
                });
                if(selCustomIndex == 0){
                  customTimes[0] = DateTime(int.parse(years[yearSelindex]), customTimes[0].month, customTimes[0].day);
                }else if(selCustomIndex == 1){
                  customTimes[1] = DateTime(int.parse(years[yearSelindex]), customTimes[1].month, customTimes[1].day);
                }
                _getYears();
                _getMonths();
                _getDays();
              },values: years,selIndex: yearSelindex,))
            ],
          ))
        ],
      ),
    );
  }

   List years = [];
   List months = [
     'Jan'.tr,
     'Feb'.tr,
     'Mar'.tr,
     'Apr'.tr,
     'May'.tr,
     'Jun'.tr,
     'Jul'.tr,
     'Aug'.tr,
     'Sep'.tr,
     'Oct'.tr,
     'Nov'.tr,
     'Dec'.tr,
   ];
   List days = [];

   int daySelindex = 0;
   int monthSelindex = 0;
   int yearSelindex = 0;

   int selMonthSingle = 0;
   int selYearSingle = 0;

   int startCustomIndex = -1;
   int endCustomIndex = -1;
   int selCustomIndex = -1;


   void _getMonths(){
     selMonthSingle = monthTimes[0].month - 1;
     monthSelindex = customTimes[0].month - 1;
     if(selCustomIndex == 1){
       monthSelindex = customTimes[1].month - 1;
     }
     if(mounted){setState(() {});}
   }

   void _getYears(){
     years = [];
     int index = 0;
     int year = customTimes[0].year;
     if(selCustomIndex ==1){
       year = customTimes[1].year;
     }
     for(int i=2000; i<=DateTime.now().year+100; i++){
       years.add('$i');
       if(i == yearTimes[0].year){
         selYearSingle = index;
       }
       if(i == year){
         yearSelindex = index;
       }
       index++;
     }
     if(mounted){setState(() {});}
   }

   void _getDays(){

     DateTime now = DateTime.now();
     if(selCustomIndex == 0){
       now = customTimes[0];
     }else if(selCustomIndex == 1){
       now = customTimes[1];
     }
     int day = DateTime(now.year, now.month+1, 0).day;
     print('day ===$day == $now');
     days.clear();
     bool isDaySel = false;
     for(int i=1; i<=day; i++){
       days.add('$i');
       if(i == now.day){
         isDaySel = true;
         daySelindex = i-1;
       }
     }
     if(isDaySel==false){
       daySelindex = days.length-1;
     }
     if(mounted){setState(() {});}
   }

   String _getYMRStr(DateTime dateTime){
     String month = formatDate(dateTime!, [mm]);
     if(month == '01'){
       month = 'Jan'.tr;
     }else if(month == '02'){
       month = 'Feb'.tr;
     }else if(month == '03'){
       month = 'Mar'.tr;
     }else if(month == '04'){
       month = 'Apr'.tr;
     }else if(month == '05'){
       month = 'May'.tr;
     }else if(month == '06'){
       month = 'Jun'.tr;
     }else if(month == '07'){
       month = 'Jul'.tr;
     }else if(month == '08'){
       month = 'Aug'.tr;
     }else if(month == '09'){
       month = 'Sep'.tr;
     }else if(month == '10'){
       month = 'Oct'.tr;
     }else if(month == '11'){
       month = 'Nov'.tr;
     }else if(month == '12'){
       month = 'Dec'.tr;
     }
     String day = formatDate(dateTime, [dd]);
     String year = formatDate(dateTime, [yyyy]);
     return '$month $day,$year';
   }
}
